/*
 *
 * Copyright 2011-2012 University of Illinois
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

Components.utils.import("resource://oaa-cache-inspector/cache-inspector-common.js");

/**
 * @function toggleSidebar
 *
 * @memberOf OAA_CI_UTILS
 *
 * @desc Toggle the sidebar based on the ID of the corresponding toolbarbutton
 *
 * @param {String}  sidebar_id - id of the sidebar to display
 */

OAA_CI_UTILS.toggleSidebar = function (sidebar_id) {

  var toolbarbutton_id = OAA_CI_UTILS.getToolbarButtonId(sidebar_id);

  if (toolbarbutton_id == '') {
    if (OAA_CI_UTILS.last_toolbarbutton_id) toolbarbutton_id = OAA_CI_UTILS.last_toolbarbutton_id;
    else toolbarbutton_id = OAA_CI_UTILS.default_toolbarbutton;
  }

  OAA_CI_UTILS.last_toolbarbutton_id = toolbarbutton_id;


  var menuitem_id = OAA_CI_UTILS.getMenuItemId(sidebar_id);

  if (menuitem_id == '') {
    if (OAA_CI_UTILS.last_menuitem_id) menuitem_id = OAA_CI_UTILS.last_menuitem_id;
    else menuitem_id = OAA_CI_UTILS.default_menuitem;
  }

  OAA_CI_UTILS.console("current main menu id: " + menuitem_id + "   last main menu id: " + OAA_CI_UTILS.last_menuitem_id);

  OAA_CI_UTILS.last_menuitem_id      = menuitem_id;
  
  
  toggleSidebar(sidebar_id);

};

/**
 * @function toggleToolbarAndOrSidebar
 *
 * @memberOf OAA_CI_UTILS
 *
 * @desc Handle one of four possible cases:
 *       1. toolbar is visible and sidebar is visible: toggle both
 *       2. toolbar is visible and sidebar is hidden:  toggle toolbar (only)
 *       3. toolbar is hidden  and sidebar is visible: toggle sidebar (only)
 *       4. toolbar is hidden  and sidebar is hidden:  toggle both
 */

OAA_CI_UTILS.toggleToolbarAndOrSidebar = function () {

  var toolbarbutton_id;
  if (OAA_CI_UTILS.last_toolbarbutton_id) toolbarbutton_id = OAA_CI_UTILS.last_toolbarbutton_id;
  else toolbarbutton_id = OAA_CI_UTILS.default_toolbarbutton;

  var sidebar_id = OAA_CI_UTILS.getSidebarId(toolbarbutton_id);
  var sidebar = window.document.getElementById(sidebar_id);

  // alert(sidebar.id + " checked=" + sidebar.hasAttribute('checked'));
  // Firefox sets and removes the 'checked' attribute to indicate visibility
  var sidebarVisible = sidebar.hasAttribute('checked');

  var toolbar = window.document.getElementById('ID_TOOLBAR_A11Y_EVALUATOR');
  if (toolbar) {
    if (toolbar.collapsed && sidebarVisible) {
      var sidebar_id = OAA_CI_UTILS.getSidebarId(toolbarbutton_id)
      OAA_CI_UTILS.toggleSidebar(sidebar_id);
    }
    else {
      // toggle the toolbar visibility and sync the sidebar with new toolbar state
      toolbar.collapsed = !(toolbar.collapsed);
      if ((!toolbar.collapsed && !sidebarVisible) || (toolbar.collapsed && sidebarVisible)) {
        var sidebar_id = OAA_CI_UTILS.getSidebarId(toolbarbutton_id)
        OAA_CI_UTILS.toggleSidebar(sidebar_id);
      }  
    }
  }
  
  try {
    show_menu = OAA_CI_UTILS.preferences.show_menu;                              
  } catch (e) {
    show_menu = true;
  }
  
  var menu = window.document.getElementById('ID_MENU_A11Y_EVALUATOR');
  if (menu) {
    if (show_menu) menu.collapsed = toolbar.collapsed; 
    else menu.collapsed = true;
  }

};

/** 
 * @function showLog
 *
 * @memberOf OAA_CI_UTILS
 *
 * @desc shows the log information for the last evaluation
 *
 * @param  {String}  format  - String format of the the log file, valid values TEXT, XML, JSON and HTML
 */

OAA_CI_UTILS.showLog = function(format) {

  OAA_CI_UTILS.showWindowLog(window, format);

};

/** 
 * @function showAbout
 *
 * @memberOf OAA_CI_UTILS
 *
 * @desc shows the log information for the last evaluation
 *
 * @param {String}  format  - String format of the the log file, valid values TEXT, XML, JSON and HTML
 */

OAA_CI_UTILS.showAbout = function() {

  window.open("chrome://oaa-cache-inspector/content/about.xul", "aboutDialog", "chrome,centerscreen");
  
};



/**
 * @function showResults
 *
 * @memberOf OAA_CI_UTILS
 *
 * @desc shows the results information for the last evaluation
 *
 * @param  {String}  format - String format of the the results file, valid values TEXT, XML, JSON and HTML
 */
 
OAA_CI_UTILS.showResults = function(format) {

  if (!OAA_CI_UTILS.result) OAA_CI.evaluateDocument();

  var result = OAA_CI_UTILS.result;
  
  if (!result) return;

  var data;
      
  if ("@mozilla.org/file/directory_service;1" in Components.classes) {
    var Cc = Components.classes;
    var Ci = Components.interfaces;
    
    // file is nsIFile, data is a string
    var file = Cc["@mozilla.org/file/directory_service;1"].getService(Ci.nsIProperties).get("TmpD", Ci.nsIFile);
    
    switch (format) {

    case 'XML':
      file.append("oaa_report.xml");
      data = result.toXML();
      break;

    case 'HTML':
      file.append("oaa_report.html");
      data = result.toHTML(); 
      break;
      
    case 'TEXT':
    default:
      file.append("oaa_report.txt");
      data = result.toString();
      break;
    }  
      
    file.createUnique(Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 0666);

    // alert(file.path);
    var foStream = Cc["@mozilla.org/network/file-output-stream;1"].createInstance(Ci.nsIFileOutputStream);
    foStream.init(file, 0x02 | 0x08 | 0x20, 0666, 0);

    var converter = Cc["@mozilla.org/intl/converter-output-stream;1"].createInstance(Ci.nsIConverterOutputStream);
    converter.init(foStream, "UTF-8", 0, 0);
    converter.writeString(data);
    converter.close(); // this closes foStream
    
    var mainWindow = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)  
                       .getInterface(Components.interfaces.nsIWebNavigation)  
                       .QueryInterface(Components.interfaces.nsIDocShellTreeItem)  
                       .rootTreeItem  
                       .QueryInterface(Components.interfaces.nsIInterfaceRequestor)  
                       .getInterface(Components.interfaces.nsIDOMWindow);  
  
    mainWindow.gBrowser.addTab("file:///"+file.path);
    
    // mainWindow.open("file:///"+file.path, "report", "status=1,location=1,scrollbars,height=800,width=1024");

  }  

};


/**
 * @function setDefaultPreferences
 *
 * @memberOf OAA_CI_UTILS
 *
 * @desc Sets preferences to default values
 */


OAA_CI_UTILS.setDefaultPreferences = function () {

  var preferences = {};
  
  preferences.ruleset_id   = 'WCAG20_ARIA_TRANS';                              
  
  preferences.wcag20_level = 3;                              
    
  preferences.broken_links = false;    

  preferences.show_menu = true;
  
  OAA_CI_UTILS.setPreferences(preferences);
  
  return preferences;
}

/**
 * @function setDefaultPreferences
 *
 * @memberOf OAA_CI_UTILS
 *
 * @desc Returns preferences object with current preferences 
 *
 * @return {Object}  Object with properties representing preferences  
 */


OAA_CI_UTILS.getPreferences = function () {

  var preferences = {};
  
  var pref_manager = Components.classes["@mozilla.org/preferences-service;1"]
                                .getService(Components.interfaces.nsIPrefBranch);            
                                
  try {
    preferences.show_menu = pref_manager.getBoolPref('extensions.oaa-accessibility-evaluator.showMenu');                              
  } catch (e) {
    preferences = OAA_CI_UTILS.setDefaultPreferences();
  }


  try {
    preferences.ruleset_id = pref_manager.getCharPref('extensions.oaa-accessibility-evaluator.rulesetId');                              
  
    preferences.wcag20_level = pref_manager.getIntPref('extensions.oaa-accessibility-evaluator.wcag20Level');                              
    
    preferences.broken_links = pref_manager.getBoolPref('extensions.oaa-accessibility-evaluator.brokenLinks');    
  } catch(e) {
    preferences = OAA_CI_UTILS.setDefaultPreferences();
  }

  var menu = window.document.getElementById('ID_MENU_A11Y_EVALUATOR');
  
  if (menu) {
    menu.collapsed = !preferences.show_menu; 
  }

  return preferences;
};


OAA_CI_UTILS.setPreferences = function (preferences) {

  OAA_CI_UTILS.console("Set Preferences:");
  OAA_CI_UTILS.console("   Ruleset ID: " + preferences.ruleset_id);
  OAA_CI_UTILS.console("   WCAG Level: " + preferences.wcag20_level);
  OAA_CI_UTILS.console("  Broken Link: " + preferences.broken_links);
  OAA_CI_UTILS.console("    Show Menu: " + preferences.show_menu);

  var pref_manager = Components.classes["@mozilla.org/preferences-service;1"]
                                .getService(Components.interfaces.nsIPrefBranch);                           
  
  if (typeof preferences.ruleset_id == "string")   pref_manager.setCharPref('extensions.oaa-accessibility-evaluator.rulesetId',   preferences.ruleset_id );                              
  if (typeof preferences.wcag20_level == "number") pref_manager.setIntPref('extensions.oaa-accessibility-evaluator.wcag20Level',  preferences.wcag20_level);                              
  if (typeof preferences.broken_links == "boolean") pref_manager.setBoolPref('extensions.oaa-accessibility-evaluator.brokenLinks', preferences.broken_links);    

  if (typeof preferences.show_menu == "boolean") pref_manager.setBoolPref('extensions.oaa-accessibility-evaluator.showMenu', preferences.show_menu);                              

  var menu = window.document.getElementById('ID_MENU_A11Y_EVALUATOR');
  
  if (menu) {
    menu.collapsed = !preferences.show_menu; 
  }


};

